
#include <xc.h> 
#include <adc.h>
#include <system.h>

#include <libpic30.h>

unsigned long hres;

void clockout() {
            unsigned char c[4];

            SPI1BUF = 0;
            while(SPI1STATbits.SPIRBF==0);
            c[0] = SPI1BUF;

            SPI1BUF = 0;
            while(SPI1STATbits.SPIRBF==0);
            c[1] = SPI1BUF;

            SPI1BUF = 0;
            while(SPI1STATbits.SPIRBF==0);
            c[2] = SPI1BUF;

            c[3] = 0;
            //getsSPI1(3, c, 5000);
            //hres = c[2]+c[1]*256+c[0]*65536;

            hres = c[0];
            hres *= 256;
            hres += c[1];
            hres *= 256;
            hres += c[2];
}

int triggeradc() {
    int res = 0;

        ADC_CS = 1;
        __delay_us(D);
        ADC_CS = 0;
        __delay_us(D);

        if(!SDI) {
            clockout();
            ADC_CS = 1;
            __delay_us(D);
            ADC_CS = 0;
            __delay_us(D);

            res = 0;
        } else res = 1;

        ADC_CS = 1;
        __delay_us(D);
}

int getadc() {
        int n=50;
        int res = 0;

        __delay_us(D);
        ADC_CS = 1;
        __delay_us(D);

        ADC_CS = 0;
        __delay_us(D);

        if(!SDI) {

            float U, I, S;

            __delay_us(D);

            clockout();
            res = 1;

        } else {
            hres = 0;
        }

        __delay_us(D);
        ADC_CS = 1;

        return res;
}
